<template>
  <canvas id="mycanvas" @click="drawCoda()"></canvas>
</template>

<script>
export default {
  data() {
    return {
      pachcode: "",
    };
  },
  mounted() {
    this.drawCoda();
  },
  methods: {
    //画布移动范围
    lineX() {
      var lineX = Math.floor(Math.random() * 300);
      return lineX;
    },

    lineY() {
      var lineY = Math.floor(Math.random() * 150);
      return lineY;
    },

    drawCoda() {
      let code = "";
      var c = document.getElementById("mycanvas");
      let r1 = Math.floor(Math.random() * 255);
      let g1 = Math.floor(Math.random() * 255);
      let b1 = Math.floor(Math.random() * 255);
      var context = c.getContext("2d");
      context.fillStyle = "#ccc";
      //阴影
      context.fillRect(0, 0, 300, 150);
      context.fillStyle = "red";
      let text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
      context.font = "100px 黑体";
      // context.rotate((Math.random() * 8 * Math.PI) / 180);
      context.fillStyle = "rgb(" + r1 + "," + g1 + "," + b1 + ")";
      //得到随机验证码
      for (let i = 0; i < 4; i++) {
        code += text[Math.floor(Math.random() * text.length)];
      }
      this.pachcode = code;
      context.fillText(code[0], 20, 100);
      let r2 = Math.floor(Math.random() * 255);
      let g2 = Math.floor(Math.random() * 255);
      let b2 = Math.floor(Math.random() * 255);

      context.font = "100px 黑体";
      // context.rotate((Math.random() * 8 * Math.PI) / 180);
      context.fillStyle = "rgb(" + r2 + "," + g2 + "," + b2 + ")";
      context.fillText(code[1], 100, 100);
      let r3 = Math.floor(Math.random() * 255);
      let g3 = Math.floor(Math.random() * 255);
      let b3 = Math.floor(Math.random() * 255);

      context.font = "100px 黑体";
      // context.rotate((Math.random() * -8 * Math.PI) / 180);
      context.fillStyle = "rgb(" + r3 + "," + g3 + "," + b3 + ")";
      context.fillText(code[2], 200, 100);
      let r4 = Math.floor(Math.random() * 255);
      let g4 = Math.floor(Math.random() * 255);
      let b4 = Math.floor(Math.random() * 255);
      context.font = "100px 黑体";

      // context.rotate((Math.random() * -8 * Math.PI) / 180);
      context.fillStyle = "rgb(" + r4 + "," + g4 + "," + b4 + ")";
      context.fillText(code[3], 250, 100);
      for (var i = 1; i <= 20; i++) {
        let r = Math.floor(Math.random() * 255);
        let g = Math.floor(Math.random() * 255);
        let b = Math.floor(Math.random() * 255);
        context.beginPath();
        context.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
        context.moveTo(this.lineX(), this.lineY());
        context.lineTo(this.lineX(), this.lineY());
        context.lineWidth = 0.5;
        context.closePath();
        context.stroke();
      }
    },
  },
};
</script>

<style scoped>
  #mycanvas {
    width: 100px;
    height: 38px;
    border: 1px solid black;
  }
</style>
